
/*
 * @Description: Test07
 * @Author: rendc
 * @Date: 2025-03-14 11:28:58
 * @LastEditors: rendc
 * @LastEditTime: 2025-03-14 14:24:07
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Test07 {

  public static void main(String[] args) {
    // 源⽂件所在路径
    String dirPath = "./";
    // 源⽂件名称
    String fileName = "img.jpg";
    // 复制数量
    int number = 10;
    // 完成剩余代码编写
    // 创建目录对象
    File dir = new File(dirPath);
    // 创建文件对象
    File img = new File(dir, fileName);
    // 创建输入流对象
    InputStream iS = null;
    // 创建输出流对象
    OutputStream[] outputStreams = new OutputStream[number];
    try {
      // 初始化输入流
      iS = new FileInputStream(img);
      // 初始化输出流
      for (int i = 0; i < outputStreams.length; i++) {
        // img_copy i
        // 获取原始文件名 img.jpg
        String[] fileNames = fileName.split("\\.");
        String name = fileNames[0];
        String suffix = fileNames[1];
        String newFileName = name + "_copy" + (i + 1) + "." + suffix;
        System.out.println("newFileName:" + newFileName);
        OutputStream oS = new FileOutputStream(newFileName);
        // 将输出流对象保存到数组中
        outputStreams[i] = oS;
      }
      // 开始复制
      // 创建缓存的数组
      byte[] buf = new byte[1024];
      // 定义变量记录读到的字节数
      int len;
      while ((len = iS.read(buf)) != -1) {
        for (OutputStream os : outputStreams) {
          os.write(buf, 0, len);
        }
      }
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    } finally {
      // 关闭资源 后开的先关 先开的后关
      // 关闭输出流
      for (OutputStream os : outputStreams) {
        if (os != null) {
          try {
            os.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
      // 关闭输入流
      if (iS != null) {
        try {
          iS.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}